<?php
App::uses('AppController', 'Controller');

/**
 * Users Controller
 *
 * @property User $User
 */
class UsersController extends AppController {

	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('admin_logout');
	}
	
	public function admin_index() {
	}
	
	public function admin_edit($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException('Invalid user');
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash('The user has been saved');
				$url = $this->Session->read('Controller.toUrl');
				$this->redirect($url);
			} else {
				$this->Session->setFlash('The user could not be saved. Please, try again.');
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
			unset($this->request->data['User']['password']);
		}
	}

	public function ajax_index(){
		$this->paginate = array(
			'recursive' => -1,
			'limit' => 10,
			'order' => array('User.username' => 'ASC')
		);
		$this->set('users', $this->paginate());
	}
	
	public function api_add() {
		$error = -1;
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$error = 0;
				$message = 'The user has been saved';
			} else {
				$error = 1;
				$message = 'The user could not be saved. Please, try again.';
			}
		}
		$this->set('error', $error);
		$this->set('data', $message);
	}
	
	public function api_delete($id = null) {
		$error = -1;
		$this->User->id = $id;
		if (!$this->User->exists()) {
			$message = 'Invalid user';
		}
		if ($this->User->delete()) {
			$error = 0;
			$message = 'User deleted';
		}
		else{
			$error = 1;
			$message = 'User was not deleted';			
		}
		$this->set('error', $error);
		$this->set('data', $message);
	}

	public function admin_login() {
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				$this->redirect($this->Auth->redirect());
			} else {
				$this->Session->setFlash(__('Invalid username or password, try again'));
			}
		}
	}

	public function admin_logout() {
		$this->redirect($this->Auth->logout());
	}
}
?>